﻿using AppDataStruct;
using ComUIControl;
using EECMISWS;
using KWindow.KPageCore;
using LogLib;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageCheckPersonInfo : PageControlBase
    {     
        //private Stopwatch sw = new Stopwatch();

        private SFZInfo _sfz = new SFZInfo();

        private bool _checkResult = false;

        private PreApplyInfo _appInfo = null;

        private WebDataAccess _webAccess = null;

        private PictureBox pictureBox1 = null;

        private Image imgChecking = null;

        private Image imgCheckFailed = null;

        private Label labelInputTip = null;

        private bool _bCancellFlag = false;

        private PersonCheckOption _option = new PersonCheckOption();

        public PageCheckPersonInfo()
        {
            InitializeComponent();
            SetProcessBase(ProcessCheckPersonInfo.Instance);
        }

        private void LoadConfig()
        {
            if(!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();
        }

        private void GetControls()
        {
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            imgCheckFailed = GetImage("CheckFailed");
            imgChecking = GetImage("Checking");
            labelInputTip = GetControl<Label>("labelInputTip") as Label;
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            LoadConfig();
            base.InitCtrls();
            GetControls();          
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            _bCancellFlag = false;
            pictureBox1.Image = imgChecking;
            _webAccess = WebDataAccess.Instance;
            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");
            _checkResult = false;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            Process.SetValue("PreApplyInfo", _appInfo);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        private void SetTips(string content)
        {
            labelInputTip.Text = content;
            int w = labelInputTip.Width;
            int x = (this.Width - w) / 2;
            labelInputTip.Left = x;
        }
        public override void StartWork()
        {
            base.StartWork();
            if (IsMainPage)
            {
                BeginChecking();
            }
            
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            _bCancellFlag = true;
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnNext_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            _bCancellFlag = true;
            StopCountdown();
            AbortWork();
            base.btnCancel_Click(sender, e);
        }

        private void BeginChecking()
        {
            if (_sfz == null)
            {
                MsgBox.Show("无有效的身份证信息.");
                return;
            }
            WebDataAccess webAccess = WebDataAccess.Instance;
            if (!webAccess.Enabled)
            {
                MessageBox.Show("全国版接口未启用.");
                base.btnNext_Click(null, null);
                return;
            }
            Task.Factory.StartNew(() =>
            {
                CheckPersonInfo();
            });
        }

        private void CheckPersonInfo()
        {          
            if (!_webAccess.Inited)
            {
                if (!_webAccess.Login())
                {
                    OnCheckFailed(_webAccess.ErrorMessage);
                    return;
                }
            }
            PeopleCheckResult result = _webAccess.CheckPersonInfo(_sfz.SFZH, _sfz.Name,_sfz.Sex_Code,_sfz.BirthDate);
            if (_bCancellFlag)
            {
                return;
            }
            if (!result.Success)
            {
                OnCheckFailed(_webAccess.ErrorMessage);
                return;
            }
            if(_bCancellFlag)
            {
                return;
            }
            UpdatePersonInfo(result);
            OnCheckCompleted(result);
            return;
        }

        private void UpdatePersonInfo(PeopleCheckResult result)
        {
            Log.WriteAsync("Update check person info from result...");
            if(result.CheckSpecialListResult == CheckResult.Yes)
            {
                _appInfo.KZDX = "1";
                string msg = string.Format("核查是控制对象, XM:{0}, SFZH:{1}",
                  _sfz.Name, _sfz.SFZH);
                Log.WriteAsync(msg);
            }
            else
            {
                _appInfo.KZDX = "0";           
                Log.WriteAsync("核查不是控制对象");
            }
            if(result.CheckOfficalResult == CheckResult.Yes)
            {
                _appInfo.GJGZRYDW = result.Offical.RSZGDW;
                string msg = string.Format("核查是国家工作人员, XM:{0}, DW:{1}",
                    result.Offical.ZWXM, result.Offical.RSZGDW);
                Log.WriteAsync(msg);
            }            
        }
        private void OnCheckCompleted(PeopleCheckResult result)
        {
            _checkResult = true;
            Log.WriteAsync("核查个人信息成功");
            Action handler = () =>
            {
                if (result.CheckSpecialListResult == CheckResult.Yes)
                {
                    MsgBox.Show("抱歉，您不能在本机办理。\n请咨询前台工作人员。");
                    ClearData();
                    Process.ToHome();
                    return;
                }
                else if(result.CheckSpecialListResult == CheckResult.Failed)
                {
                    string msg = string.Format("核查个人信息失败: \n{0}", result.ErrorMessage);
                    MsgBox.Show(msg);
                    SetTips(msg);
                    CountdownSecond = 10;
                    StartCountdown();
                    return;
                }
                if(_option.EnabledCheckOffical)
                {
                    if (result.CheckOfficalResult == CheckResult.Yes)
                    {
                        string info = string.Format("请注意: 您是国家工作人员, \n工作单位是:\t{0}", result.Offical.RSZGDW);
                        MsgBox.Show(info);
                        UpdateData();
                        ClearData();
                        StopCountdown();
                        Process.ToNext();
                        return;
                    }
                    else if (result.CheckOfficalResult == CheckResult.No)
                    {
                        UpdateData();
                        ClearData();
                        StopCountdown();
                        Process.ToNext();
                        return;
                    }
                    else
                    {
                        string msg = string.Format("核查个人信息失败: \n{0}", result.ErrorMessage);
                        MsgBox.Show(msg);
                        SetTips(msg);
                        CountdownSecond = 10;
                        StartCountdown();
                    }
                }
                else
                {                
                    UpdateData();
                    ClearData();
                    StopCountdown();
                    Process.ToNext();
                    return;
                }
            };
            this.Invoke(handler);
        }

        private void OnCheckFailed(string outParams)
        {
            if (_bCancellFlag)
            {
                return;
            }
            string msg = string.Format("核查个人信息失败: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                pictureBox1.Image = imgCheckFailed;
                SetTips(msg);
                CountdownSecond = 10;
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }
    }
}
